package cn.cloudtogo.common.types;

import cn.cloudtogo.common.model.DatasourceTypes;
import cn.cloudtogo.common.util.StringHelper;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotBlank;

/**
 * @author yaolianhua789@gmail.com
 **/
@Data
public class DatasourceCreateObject {

    private String url;
    private String project;

    private Credential credential;
    private Endpoint endpoint;

    private DatasourceTypes type = DatasourceTypes.Mysql;
    @NotBlank(message = "open id is null")
    private String openid;
    @NotBlank(message = "schema name is null")
    private String schema;
    @NotBlank(message = "component name is null")
    @JsonProperty("component")
    private String name;

    public ConnectString getConnectString() {
        if (StringUtils.hasText(this.url)) {
            return ConnectString.getConnectString(this.url);
        } else {
            return new ConnectString(this.type, this.credential, this.endpoint, this.schema);
        }
    }

    public String obtainConnectUrl() {
        ConnectString connectString = this.getConnectString();
        return ConnectString.constructUrl(connectString);
    }

    public String obtainProject() {

        if (StringUtils.hasText(project)) {
            return project;
        }

        long currentTimeMillis = System.currentTimeMillis();
        project = StringHelper.encode("|", new String[]{url, schema, openid, name, String.valueOf(currentTimeMillis)});

        return project;
    }
}
